package io.gitee.h25094152.json;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONPath;
import io.gitee.h25094152.string.StringExtUtils;

import java.util.ArrayList;
import java.util.List;

public class JsonUtil<T> {

    /**
     * 解析 JSON 到List
     *
     * @param jsonArray
     * @param param
     * @return
     */
    public static List<String> jsonPathArray(JSONArray jsonArray, String param) {
        return jsonPathArray(jsonArray, param, String.class);
    }

    public static <T> List<T> jsonPathArray(String json, String param, Class<T> clazz)  {
        Object object = JSON.parse(json);
        if (object instanceof JSONObject) {
            JSONObject jsonObject = (JSONObject) object;
            return jsonPathArray(jsonObject, param, clazz);
        } else if (object instanceof JSONArray) {
            JSONArray jsonArray = (JSONArray) object;
            return jsonPathArray(jsonArray, param, clazz);
        }
        return null ;
    }

    public static <T> List<T> jsonPathArray(Object jsonArray, String param, Class<T> clazz) {
        List<T> list;
        list = new ArrayList<T>();
        Object eval = JSONPath.eval(jsonArray, param);

        if(eval instanceof List){
            list = (List<T>)eval ;
        }else{
            list.add((T)eval);
        }

        return list;
    }

    /**
     * 解析Json 到 String
     *
     * @param jsonObject
     * @param param
     * @return
     */
    public static String jsonPathObject(JSONObject jsonObject, String param) {
        return jsonPathObject(jsonObject, param, String.class);
    }


    public static <T> T jsonPathObject(String json, String param, Class<T> clazz) {

        Object object = JSON.parse(json);
        if (object instanceof JSONObject) {
            JSONObject jsonObject = (JSONObject) object;
            return jsonPathObject(jsonObject, param, clazz);
        } else if (object instanceof JSONArray) {
            JSONArray jsonArray = (JSONArray) object;
            return jsonPathObject(jsonArray, param, clazz);
        }
        return null ;

    }

    public static <T> T jsonPathObject(Object jsonObject, String param, Class<T> clazz) {
        return clazz.cast(JSONPath.eval(jsonObject, param));
    }






}
